package cn.wizzer.app.web.commons.utils;

import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.user.modules.models.constant.UserConstant;
import cn.wizzer.app.user.modules.models.enums.EquipmentEnum;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 22099
 */
//假冒伪劣tokenUtil
@IocBean(singleton = false, name = "tokenUtil")
public class TokenUtilImpl extends TokenUtil {

    static long oneHour = 1000 * 60 * 60;
    static long oneDay = 1000 * 60 * 60 * 24;

    @Inject
    private RedisService redisService;

    @Inject
    @Reference
    private SysParamService sysParamService;

    public String generateToken(Date date, String appid, EquipmentEnum equipment) throws IOException, ClassNotFoundException {
        if (equipment == null) {
            equipment = EquipmentEnum.MOBILE;
        }
        String token = super.generateToken(date, appid);
        //验证已登录设备中相同设备以做离线处理
        List<String> keys = RedisUtil.scan(UserConstant.getSampleRedisKeyToken(appid,equipment));
        if (keys.size()>0){
            //除当前token以外全部失效
            RedisUtil.del(keys.stream().collect(Collectors.joining(",")).split(","));
        }
        //设置过期时间到redis
        String redisKeyToken = UserConstant.getRedisKeyToken(appid, token, equipment);
        RedisUtil.set(redisKeyToken, date.getTime());
        return token;
    }

    public boolean verifyToken(String appid, String token, EquipmentEnum equipment) {
        if (sysParamService.fetch().isDebug()) {
            return Strings.isNotBlank(appid);
        }
        if (equipment == null) {
            equipment = EquipmentEnum.MOBILE;
        }
        String redisKeyToken = UserConstant.getRedisKeyToken(appid, token, equipment);
        String expireTime = RedisUtil.get(redisKeyToken);
        //未登录
        if (Strings.isEmpty(expireTime)) {
            return false;
        }
        long current = System.currentTimeMillis();
        long value = new Long(expireTime) - current;
        //登录超时
        if(value<=0){
            return false;
        }
        //更新过期时间到redis
        int loginValidTime = sysParamService.fetch().getLoginValidTime();
        long currentTimeStamp = System.currentTimeMillis();
        long usefulTimeStamp = loginValidTime * 60 * 1000;
        if (currentTimeStamp - Long.parseLong(redisService.get(redisKeyToken)) <= usefulTimeStamp / 2) {
            //设置token有效期为10分钟
            redisService.set(redisKeyToken, String.valueOf(currentTimeStamp + usefulTimeStamp));
        }
        return true;
    }
}
